package com.springapi.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.springapi.entity.Goodsmanager;
import com.springapi.dao.GoodsmanagerDao;
import com.springapi.service.GoodsmanagerService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (Goodsmanager)表服务实现类
 *
 * @author makejava
 * @since 2024-12-13 08:05:20
 */

@Service("goodsmanagerService")
public class GoodsmanagerServiceImpl implements GoodsmanagerService {
    @Resource
    private GoodsmanagerDao goodsmanagerDao;

    @Value("${filesavepath}")
    private String FILE_SAVE_PATH;
    @Value("${filesavefilepath}")
    private String FILE_SAVE_FILE_PATH;

    @Override
    public List<Goodsmanager> getgoodsbyinventory(int appid, int shopid, int limitint) {
        return goodsmanagerDao.getgoodsbyinventory(appid,shopid,limitint);
    }

    /**
     * 通过appid和shopid分页查询数据
     */
    @Override
    public PageInfo<Goodsmanager> myfindAll(int appid, int shopid, int page, int size, int goodsclassoneid, int goodsclasstwoid) {
        long total2=goodsmanagerDao.myfindAll(appid,shopid,goodsclassoneid,goodsclasstwoid).size();
        System.out.println("数据总条数total："+total2);

        // 这句代码要放在查询 mapper 语句的前面
        PageHelper.startPage(page, size);
        Pageable pageable = PageRequest.of(page, size);
        List<Goodsmanager> goodsManagers = goodsmanagerDao.myfindAll(appid,shopid,goodsclassoneid,goodsclasstwoid);
        PageInfo<Goodsmanager> pageInfo = new PageInfo<>(goodsManagers);
        return  pageInfo;
    }


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Goodsmanager queryById(Integer id) {
        return this.goodsmanagerDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param goodsmanager 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<Goodsmanager> queryByPage(Goodsmanager goodsmanager, PageRequest pageRequest) {
        long total = this.goodsmanagerDao.count(goodsmanager);
        return new PageImpl<>(this.goodsmanagerDao.queryAllByLimit(goodsmanager, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param goodsmanager 实例对象
     * @return 实例对象
     */
    @Override
    public Goodsmanager insert(Goodsmanager goodsmanager) {

        //获取商品首图并判断首图是否为空
        String topimg = goodsmanager.getTopimg();
        if (topimg != null) {
            // 定义源文件路径和目标文件路径
            Path sourcePath = Paths.get(FILE_SAVE_PATH+"/"+topimg);
            System.out.println("sourcePath:"+sourcePath);
            Path targetPath = Paths.get(FILE_SAVE_FILE_PATH+"/"+topimg);
            System.out.println("targetPath:"+targetPath);
            try {
                // 确保目标目录存在（如果不存在则创建）
                Path targetDirectory = targetPath.getParent();
                if (targetDirectory != null && !Files.exists(targetDirectory)) {
                    Files.createDirectories(targetDirectory);
                }

                // 移动文件（剪切+粘贴）
                Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);

                System.out.println("文件已成功移动到目标目录！");
            } catch (IOException e) {
                System.err.println("文件移动失败: " + e.getMessage());
                e.printStackTrace();
            }

        }

        this.goodsmanagerDao.insert(goodsmanager);
        return goodsmanager;
    }

    /**
     * 修改数据
     *
     * @param goodsmanager 实例对象
     * @return 实例对象
     */
    @Override
    public Goodsmanager update(Goodsmanager goodsmanager) {
        //获取前台传过来的新首图名称
        String  topimg = goodsmanager.getTopimg();
        //获取前台传过来的商品id
        Integer id=goodsmanager.getId();
        //根据id查找数据库商品信息并获取数据库中首图名称
        Goodsmanager goodsmanager2=this.goodsmanagerDao.queryById(id);
        String  topimg2=goodsmanager2.getTopimg();
        //对比首图名称有没有变化，如果有变化，删除已保存图片，并从临时文件夹剪切新图片到保存文件夹
        if(topimg.equals(topimg2)){
            System.out.println("首图名称相等没有变化不做处理");
        }else{
            //拼接新图片地址以及新图片剪切地址
            Path topimgPath = Paths.get(FILE_SAVE_PATH+"/"+topimg);
            Path savePath = Paths.get(FILE_SAVE_FILE_PATH+"/"+topimg);
            try {
                // 确保目标目录存在（如果不存在则创建）
                Path targetDirectory = savePath.getParent();
                if (targetDirectory != null && !Files.exists(targetDirectory)) {
                    Files.createDirectories(targetDirectory);
                }
                // 移动文件（剪切+粘贴）
                Files.move(topimgPath, savePath, StandardCopyOption.REPLACE_EXISTING);

                System.out.println("文件已成功移动到目标目录！");
            } catch (IOException e) {
                System.err.println("文件移动失败: " + e.getMessage());
                e.printStackTrace();
            }
            // 拼接数据库首图路径
            Path topimg2Path = Paths.get(FILE_SAVE_FILE_PATH+"/"+topimg2);
            try {
                // 删除文件
                Files.delete(topimg2Path);
                System.out.println("文件已成功删除: " + topimg2Path);
            } catch (IOException e) {
                System.err.println("删除文件时出错: " + e.getMessage());
            }
        }
       // System.out.println("id==========:"+goodsmanager.getId());
        this.goodsmanagerDao.update(goodsmanager);
        return this.queryById(goodsmanager.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.goodsmanagerDao.deleteById(id) > 0;
    }
}
